import React from "react";
import { Modal, Button, Row, Card, Col, Form, Tree, Spin, Checkbox, Input } from "antd";
import { connect } from "dva";
import UsersTags from "components/usersTags/UsersTags";
import yujing from "../../assets/images/yujing.png";
import { openNotificationWithIcon, getOrgName } from "../../utils/comm.js";
import styles from "./NoticeUserAdd.less";

const { TreeNode } = Tree;
const formItemLayout = { labelCol: { span: 7 }, wrapperCol: { span: 16 } };
const keyReducer = (map,key) => {
  map[key] = true;
  return map;
};
@Form.create()
class NoticeUserAddModal extends React.Component {

  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon;

    this.state = {
      treeData: [],
      checkedKeys: [], // 当前tree已经加载的数据中选中的key
      checkedUsers: [], // 所有选中的人
    };
  }

  componentDidMount() {
    this.getRootOrg();
    const { users = [] } = this.props;
    this.setState({ checkedUsers: users });
    this.loadMessageTheme();
  }

  getRootOrg = () => {
    const { dispatch } = this.props;
    dispatch({
      type: "usertreeSelect/getRootOrg",
      payload: {},
    }).then(({ errCode, datas }) => {
      if (errCode !== 0) {
        this.openNotificationWithIcon("error", "", "获取根组织信息失败");
      } else {
        this.setState({ treeData: Array.isArray(datas) ? datas : [datas] });
      }
    });
  };

  doCheckTree = (checkedKeys, { checked, checkedNodes }) => {
    const { checkedKeys: prevCheckedKeys, checkedUsers } = this.state;
    if (checked) {
      const prevKeyMap = prevCheckedKeys.reduce(keyReducer, {});
      const addedKeyMap = checkedKeys.filter(key => !prevKeyMap[key]).reduce(keyReducer, {});
      const newCheckedUsers = [...checkedUsers];
      checkedNodes.forEach((item) => {
        if (addedKeyMap[item.key]) {
          newCheckedUsers.push({
            userCode: item.key,
            userName: item.props.title,
            userOrgDesc: item.props.orgsArr.join('/'),
          })
        }
      });
      this.setState({
        checkedKeys,
        checkedUsers: newCheckedUsers,
      });
    } else { const currentKeyMap = checkedKeys.reduce(keyReducer, {});

      const removedKeyMap = prevCheckedKeys.filter(key => !currentKeyMap[key]).reduce(keyReducer, {});
      this.setState({
        checkedKeys,
        checkedUsers: checkedUsers.filter(({ userCode }) => !removedKeyMap[userCode]),
      });
    }
  }

  handleLoadData = (treeNode) =>
    new Promise((resolve) => {
      const { dispatch } = this.props;
      const { treeData, checkedKeys, checkedUsers } = this.state;
      if (treeNode.props.children) {
        resolve();
        return;
      }
      const orgCode = treeNode.props.dataRef.code;
      const orgName = treeNode.props.dataRef.displayName;
      dispatch({
        type: "usertreeSelect/getChildren",
        payload: { pageNo: 1, pageSize: 1000, orgCode, orgName },
      }).then(({ errCode, uerrCode, uerrMsg, errMsg, datas }) => {
        if (errCode !== 0) {
          this.openNotificationWithIcon(
            "error",
            "",
            errMsg || "获取子组织信息失败",
          );
        }
        if (uerrCode !== 0) {
          this.openNotificationWithIcon(
            "error",
            "",
            uerrMsg || "获取人员信息失败",
          );
        }
        if (datas.length > 0) {
          treeNode.props.dataRef.children = datas;
          // 反显处理
          const loadedSelectedKeys = checkedUsers.filter(({ userCode: checkedCode }) => {
            return datas.some((citem) => citem.code === checkedCode);
          });
          const newKeys = [...checkedKeys, ...loadedSelectedKeys];
          // this.loadedKeys = this.loadedKeys.concat(datas);
          this.setState({
            treeData: [...treeData],
            checkedKeys: newKeys,
          });
          resolve();
        }
        resolve();
      });
    });

  renderTreeNodes = (data, parentOrgs = []) =>
    data.map((item) => {
      if (item.children) {
        return (
          <TreeNode
            disableCheckbox={!item.isLeaf}
            title={item.displayName}
            key={item.code}
            dataRef={item}
            orgsArr={parentOrgs}
          >
            {this.renderTreeNodes(item.children, parentOrgs.concat(getOrgName(item)))}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          disableCheckbox={!item.isLeaf}
          title={item.displayName}
          key={item.code}
          dataRef={item}
          isLeaf={item.isLeaf}
          orgsArr={parentOrgs}
        />
      );
    });

  handleDelete = (record) => {
    const { checkedUsers } = this.state;

    const afterCheckedUsers = checkedUsers.filter(
      (item) => item.userCode !== record.userCode,
    );
    this.setState({ checkedUsers: afterCheckedUsers });
  }

  handleOk = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    const { onOk } = this.props;
    const { checkedUsers } = this.state;
    onOk(checkedUsers)
    this.handleCancel();
  };

  handleCancel = (isQuery) => {
    const { handleCancel } = this.props;
    handleCancel(false, isQuery);
  };

  tagClose = (removedTag) => {
    const { checkedKeys, checkedUsers } = this.state;

    this.setState({
      checkedUsers: checkedUsers.filter(
        (item) => item.userCode !== removedTag.userCode,
      ),
      checkedKeys: checkedKeys.filter(key => key !== removedTag.userCode),
    });
  }

  loadMessageTheme = () => {
    const { dispatch, form, noticeThemeTypeList, type, noticeType } = this.props;
    const typeValue = type === '流程' ? 'FLOW' : 'NODE';
    const noticeThemeTypes = (noticeThemeTypeList || []).filter(({ value, type: _type }) => _type === typeValue && (value || '').indexOf(noticeType) > -1);
    if (noticeThemeTypes.length > 0) {
      dispatch({
        type: 'notice_msg/getNoticeTheme',
        payload: {
          type: typeValue,
          noticeThemCode: noticeThemeTypes[0].key,
        },
      }).then(({ datas }) => {
        if (datas && datas.length > 0) {
          form.setFieldsValue({ messageThemName: datas[0].messageThemName });
        }
        form.validateFields();
      });
    } else {
      form.validateFields();
    }
  }

  renderNoticeTheme = () => {
    const { form, loadingMessageTheme } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Spin spinning={!!loadingMessageTheme}>
        <Form.Item label="通知消息主题：">
          {getFieldDecorator("messageThemName", {
            rules: [
              { required: true, message: "请联系管理员配置对应的通知消息主题" },
            ],
          })(<Input disabled />)}
        </Form.Item>
      </Spin>
    );
  }

  renderNoticeUsers(disabled) {
    const { checkedUsers } = this.state;

    return (
      <Row type="flex" align="middle">
        <Checkbox checked disabled>发起人</Checkbox>
        {checkedUsers.map((item) => {
          return (
            <UsersTags
              key={`${item.userCode}`}
              label={item.userName}
              onClick={() => this.tagClose(item)}
              disabled={disabled}
            />
          );
        })}
      </Row>
    );
  }

  renderFooter = () => {
    return (
      <div>
        <Button style={{ marginRight: 10 }} onClick={this.handleCancel}>
          取消
        </Button>
        <Button
          type="primary"
          onClick={() => {
            this.handleOk();
          }}
        >
          确认
        </Button>
      </div>
    );
  }

  render() {
    const { visible, type, noticeType, disabled,loading: { effects } } = this.props;
    const { treeData, checkedKeys } = this.state;

    const rootLoading = effects["usertreeSelect/getRootOrg"] || false;
    const title = `${type}${noticeType}通知设置`;

    return (
      <Modal
        title={title}
        visible={visible}
        onOk={this.handleOk}
        onCancel={() => {
          this.handleCancel(false);
        }}
        footer={this.renderFooter()}
        width="800px"
        centered
        wrapClassName={styles.modal}
      >
        <Row style={{ height: 412 }} gutter={16}>
          <Col span={8}>
            <Card
              size="small"
              title="选择通知人"
              style={{ height: "100%" }}
              bodyStyle={{ height: 373, overflow: "auto" }}
            >
              <Spin spinning={rootLoading}>
                <div className={styles.user_tree}>
                  {treeData.length > 0 && (
                    <Tree.DirectoryTree
                      checkable
                      loadData={this.handleLoadData}
                      onCheck={this.doCheckTree}
                      checkedKeys={checkedKeys}
                    >
                      {this.renderTreeNodes(treeData)}
                    </Tree.DirectoryTree>
                  )}
                </div>
              </Spin>
            </Card>
          </Col>
          <Col span={16} style={{textAlign: 'center'}}>
            <img src={yujing} alt="" />
            <Form {...formItemLayout} className={styles.form}>
              { this.renderNoticeTheme() }
              <div className={styles.last}>
                <Form.Item label="消息接收人：">
                  {this.renderNoticeUsers(disabled)}
                </Form.Item>
              </div>
            </Form>
          </Col>
        </Row>
      </Modal>
    );
  }
}

export default NoticeUserAddModal;
